package com.linhui.project.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.linhui.project.model.entity.Post;
import com.linhui.project.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: 临晖
 * @since: 2024-05-18
 */

// 取消注释后，每次启动springboot项目会执行因此run方法
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {


    @Resource
    private PostService postService;



    @Override
    public void run(String... args) throws Exception {
        String json = "{\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"reviewStatus\":1,\"current\":30}";
        String url = "https://api.code-nav.cn/api/post/list/page/vo";

        String result = HttpRequest.post(url)
                .body(json)
                .execute()
                .body();
        System.out.println(result);

        Map<String, Object> map = JSONUtil.toBean(result, Map.class);

        JSONObject data = (JSONObject) map.get("data");
        JSONArray array = (JSONArray) data.get("records");
        ArrayList<Post> postList = new ArrayList<>();
        for (Object obj : array) {
            JSONObject tempObj = (JSONObject) obj;
            Post post = new Post();
            post.setTitle(tempObj.getStr("title"));
            post.setContent(tempObj.getStr("content"));
            JSONArray tags = (JSONArray) tempObj.get("tags");
            List<String> tagList = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(tagList));
            post.setUserId(1L);
            postList.add(post);
        }

        //插入数据库
        boolean res = false;
        try {
            res = postService.saveBatch(postList);
            log.info("FetchInitPostList获取初始化帖子列表成功，条数={}", postList.size());
        } catch (Exception e) {
            log.error("FetchInitPostList获取初始化帖子列表失败");
        }


    }
}
